package cn.itcast.consumer.web;

import cn.itcast.consumer.client.UserClient;
import cn.itcast.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("consumer")
//@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

    @Autowired
    private UserClient userClient;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id) {
        return userClient.queryById(id);
    }

    /*@HystrixCommand(commandProperties = {
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000")
    })
//    @HystrixCommand
    @GetMapping("{id}")
    public String queryById(@PathVariable("id") Long id) {
        // 人为判断成功或失败
        if (id == 1) {
            throw new RuntimeException();
        }
        // 准备URL地址
        String url = "http://user-service/user/" + id;
        return restTemplate.getForObject(url, String.class);
    }

    public String defaultFallback() {
        return "别挤了！服务器太忙了！";
    }*/

   /* @Autowired
    private DiscoveryClient discoveryClient;

    int index = 0;

    @GetMapping("{id}")
    public User queryById(@PathVariable("id") Long id) {
        // 服务列表的拉取
        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        // TODO 利用负载均衡算法，获取服务
        // int index = new Random().nextInt(instances.size());
        index = (index + 1) % instances.size();
        ServiceInstance instance = instances.get(index);

        // 获取实例的地址信息
        String host = instance.getHost();
        int port = instance.getPort();
        // 准备URL地址
        String url = String.format("http://%s:%d/user/%d", host, port, id);
        return restTemplate.getForObject(url, User.class);
    }*/

}
